package com.flyxteam.supports.distributed.trace;

import java.util.UUID;

/**
 * traceId管理工具类
 * <ul>
 * <li>2017-04-28 | yuzh | + create</li>
 * </ul>
 * @author yuzh
 */
public class TraceIdManager {

	private final static ThreadLocal<String> traceIdThreadLocal = new ThreadLocal<String>();
	private final static String TRACE_ID_PRE = "trace_id_";
	
	private static TraceIdManager traceIdManager = null;
	
	public static TraceIdManager getInstence() {
		if(traceIdManager == null) {
			synchronized (TraceIdManager.class) {
				if(traceIdManager == null) {
					traceIdManager = new TraceIdManager();
				}
			}
		}
		
		return traceIdManager;
	}
	
	//TODO 并发环境下可能会出现重复的traceId
	public String generate() {
		return TRACE_ID_PRE + UUID.randomUUID().toString().replace("-", "");
	}
	
	public String generateAndSet() {
		String traceId = generate();
		set(traceId);
		return traceId;
	}

	public void remove() {
		traceIdThreadLocal.remove();
	}
	
	public void set(String traceId) {
		traceIdThreadLocal.set(traceId);
	}
	
	public String get() {
		return traceIdThreadLocal.get();
	}

}
